package com.feng.fengDUtil.dao;

import com.feng.fengDUtil.Reflections;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.UUID;

public class IdHelp {
    public IdHelp() {
    }

    public static String setIdUuid(Field idField, Object bean) {
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        Reflections.setFieldValue(bean, idField, uuid);
        return uuid;
    }

    public static void setIdValue(Object bean, Field idField, Object dbIdValue) {
        Class type = idField.getType();
        if (type != Long.TYPE && type != Long.class) {
            if (type != Integer.TYPE && type != Integer.class) {
                throw new RuntimeException("数据库生成主键目前只支持Integer或Long类型，但数据库返回的类型为:" + type + ",值为:" + dbIdValue);
            } else {
                setIntegerValue(bean, idField, dbIdValue);
            }
        } else {
            setLongValue(bean, idField, dbIdValue);
        }
    }

    private static void setIntegerValue(Object bean, Field idField, Object dbIdValue) {
        if (dbIdValue instanceof BigDecimal) {
            BigDecimal bid = (BigDecimal)dbIdValue;
            Reflections.setFieldValue(bean, idField, bid.intValue());
        } else if (dbIdValue instanceof BigInteger) {
            BigInteger bid = (BigInteger)dbIdValue;
            Reflections.setFieldValue(bean, idField, bid.intValue());
        } else if (dbIdValue instanceof Integer) {
            Reflections.setFieldValue(bean, idField, dbIdValue);
        } else if (dbIdValue instanceof Long) {
            Reflections.setFieldValue(bean, idField, ((Long) dbIdValue).intValue());
        } else {
            throwUnMatchedException(idField, dbIdValue);
        }
    }

    private static void setLongValue(Object bean, Field idField, Object dbIdValue) {
        if (dbIdValue instanceof BigDecimal) {
            BigDecimal bid = (BigDecimal)dbIdValue;
            Reflections.setFieldValue(bean, idField, bid.longValue());
        } else if (dbIdValue instanceof BigInteger) {
            BigInteger bid = (BigInteger)dbIdValue;
            Reflections.setFieldValue(bean, idField, bid.longValue());
        } else if (dbIdValue instanceof Long) {
            Reflections.setFieldValue(bean, idField, dbIdValue);
        } else if (dbIdValue instanceof Integer) {
            Reflections.setFieldValue(bean, idField, (long)((Integer)dbIdValue).intValue());
        } else {
            throwUnMatchedException(idField, dbIdValue);
        }
    }

    private static void throwUnMatchedException(Field idField, Object dbIdValue) {
        throw new RuntimeException("不支持的数据类型转换:java字段的类型为:" + idField.getType() + ",数据库的类型为:" + dbIdValue.getClass() + ",数据库返回的值为:" + dbIdValue);
    }
}